package com.yummy.web.security.context;

import java.beans.Transient;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class AccessToken implements Session{
	/**
	 * 
	 */
	private static final long serialVersionUID = -6628973808330760597L;
	
	private String id;
	private Date createTime;
	private boolean invalid;
	private Date lastAccessedTime;
	private Long timeout;
	private TimeUnit timeUnit;
	private boolean login;
	private Map<String,Object> attributes = new HashMap<>();
	
	public AccessToken() {
		
	}
	
	public AccessToken(String id,Long timeout,TimeUnit timeUnit) {
		this.id = id;
		this.createTime = new Date();
		this.lastAccessedTime = this.createTime;
		this.invalid = false;
		this.timeout = timeout;
		this.timeUnit = timeUnit;
	}

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	public boolean isValid() {
		return !this.invalid;
	}

	@Override
	public boolean isExpired() {
		Date now = new Date();
		Date expiryTime = new Date(getLastAccessedTime().getTime()+TimeUnit.MILLISECONDS.convert(this.timeout, this.timeUnit));
		return now.compareTo(expiryTime) > 0;
	}

	@Override
	public Date getLastAccessedTime() {
		return this.lastAccessedTime;
	}

	@Override
	public Object getAttribute(String name) {
		return attributes.get(name);
	}

	@Override
	@Transient
	public Set<String> getAttributeNames() {
		return attributes.keySet();
	}

	@Override
	public void setAttribute(String name, Object value) {
		attributes.put(name, value);
	}

	@Override
	public void removeAttribute(String name) {
		attributes.remove(name);
	}

	@Override
	public void invalidate() {
		this.invalid = true;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	@Override
	public void touch() {
		this.lastAccessedTime = new Date();
	}

	public Long getTimeout() {
		return timeout;
	}
	public TimeUnit getTimeUnit() {
		return timeUnit;
	}

	public boolean isInvalid() {
		return invalid;
	}

	public void setInvalid(boolean invalid) {
		this.invalid = invalid;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public void setLastAccessedTime(Date lastAccessedTime) {
		this.lastAccessedTime = lastAccessedTime;
	}

	public void setTimeout(Long timeout) {
		this.timeout = timeout;
	}

	public void setTimeUnit(TimeUnit timeUnit) {
		this.timeUnit = timeUnit;
	}

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}
	
}
